<template>
  <!-- 简单横幅 -->
  <view v-if="show" class="simple-banner">
    <text class="banner-text">{{ text }}</text>
    <button class="close-btn" @tap="close">×</button>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const show = ref(false)
const text = ref('')

onMounted(() => {
  console.log('🎉 SimpleBanner 组件已挂载')
  console.log('🎉 当前show状态:', show.value)
  console.log('🎉 当前text内容:', text.value)
  
  // 使用UniApp的全局对象
  try {
    const app = getApp()
    if (app) {
      app.__SIMPLE_BANNER__ = {
        show: (message) => {
          text.value = message
          show.value = true
          console.log('🎉 SimpleBanner 显示:', message)
          console.log('🎉 设置后show状态:', show.value)
        },
        hide: () => {
          show.value = false
          console.log('🎉 SimpleBanner 隐藏')
        }
      }
      console.log('🎉 SimpleBanner 已暴露到app实例')
      
      // 立即检查是否有待显示的数据
      if (app.globalData && app.globalData.showBanner) {
        console.log('🎉 发现待显示的横幅数据:', app.globalData.showBanner)
        text.value = app.globalData.showBanner
        show.value = true
        app.globalData.showBanner = null
        console.log('🎉 立即显示横幅，show状态:', show.value)
      }
    }
  } catch (error) {
    console.log('🎉 无法获取app实例:', error)
  }
  
  // 监听全局数据变化
  const checkGlobalData = () => {
    try {
      const app = getApp()
      if (app && app.globalData && app.globalData.showBanner) {
        text.value = app.globalData.showBanner
        show.value = true
        console.log('🎉 SimpleBanner 通过全局数据显示:', app.globalData.showBanner)
        console.log('🎉 设置后show状态:', show.value)
        // 清除全局数据
        app.globalData.showBanner = null
      }
    } catch (error) {
      console.log('🎉 检查全局数据失败:', error)
    }
  }
  
  // 每秒检查一次全局数据
  const interval = setInterval(checkGlobalData, 1000)
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(interval)
  })
})

function close() {
  show.value = false
}
</script>

<style scoped>
.simple-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99999;
  background: #ff4444;
  color: white;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.banner-text {
  font-size: 16px;
  font-weight: bold;
  flex: 1;
}

.close-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}
</style>
